/*
 * Copyright (C) National Biorepository Project, KFSHRC, 2003
 * Created on Aug 31, 2003 by aaa
 *
 */
package sa.edu.kfshrc.nb.server.database;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.logging.Logger;

import javax.naming.Context;
import javax.naming.InitialContext;

import sa.edu.kfshrc.nb.server.Configurator;
import sa.edu.kfshrc.nb.server.exceptions.NBServerException;
import sa.edu.kfshrc.nb.server.logging.NBLevel;


/**
 * @author aaa
 * Created on Aug 31, 2003 at 5:56:25 PM.
 *
 * This class should be used to isolate any database-dependent code. It also
 * has code that is particular to all databases (e.g. getConnection).
 */
public class DatabaseWrapper
{
	// ----- Supported Databases ----------------------------------------------
	public static final String DB_POSTGRESQL = "PostgreSQL";
	
	// ----- Current database -------------------------------------------------
	private static String currentDatabase = null;
	private static String databaseJNDIName = null; 

	public static String getCurrentDatabase()
	{
		return currentDatabase;
	}

	public static String getDatabaseJNDIName()
	{
		return databaseJNDIName;
	}

	public static boolean setDatabaseParameters(String inCurrentDatabase, String inDatabaseJNDIName)
	{
		if (isSupported(inCurrentDatabase))
		{
			currentDatabase = inCurrentDatabase;
			databaseJNDIName = inDatabaseJNDIName;
			return true;
		}
		return false;
	}
	
	public static boolean isSupported(String database)
	{
		if (database != null)
		{
			if (database.equalsIgnoreCase(DB_POSTGRESQL))
				return true;
		}
		return false;		
	}
	
	public static PrimaryKey getLastPrimaryKeyGenerated(Connection connection, String tableName)
		throws NBServerException
	{
		Statement stmt = null;
		Logger mainLogger = Configurator.getMainLogger();

		try
		{
			if (currentDatabase.equalsIgnoreCase(DB_POSTGRESQL))
			{
				stmt = connection.createStatement();
				//stmt.executeQuery("select currval('" + tableName + "_id_seq')");
				stmt.executeQuery("select currval('s_global_id_seq')");

				ResultSet resultSet = stmt.getResultSet();
				if (resultSet.first())
				{
					return PrimaryKey.getFromResultSet(resultSet, "currval");
				}
				throw new NBServerException("No primary key found in result set.", false);
			}
			throw new NBServerException("Unrecognized database type.", false);
		}
		catch (Exception e)
		{
			mainLogger.log(NBLevel.NB_ERROR, "database.UnableToGetLastPrimaryKeyGenerated", e);
			throw new NBServerException("database.UnableToGetLastPrimaryKeyGenerated", true, e);
		}
		finally
		{
			try { if (stmt != null) stmt.close(); }
			catch (Exception e) {}
		}
	}

	public static Connection getConnection() throws Exception
	{
		try
		{
			Context ctx = new InitialContext();
			javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup(getDatabaseJNDIName());
			Connection connection = ds.getConnection();
			connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
			// Not necessary to do this: JBoss apparently sets it to false for you
			// conn.setAutoCommit(false);
			return connection;
		}
		catch (Exception e)
		{
			(Configurator.getMainLogger()).log(NBLevel.NB_FATALERROR, "database.UnableToEstablishConnection", e);
			throw e;
		}
	}

	/**
	 * 
	 */
	public DatabaseWrapper(String database)
	{
	}
}
